import { toSuccess, useEntityManager } from "@sker/core"
import { KsAccount, KsLiveRoom, KsRedPacket, KsAccountFollow } from "@sker/entities"
import { useData } from "@sker/runtime"
import { z } from "zod"

export default async () => {
    const input = z.object({
        userId: z.string(),
        deviceId: z.string(),
        packageName: z.string(),
        count: z.number()
    })
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const accountFollows = await m.find(KsAccountFollow, { where: { from: body.userId, package_name: body.packageName } })
        const hasFollowIds = accountFollows.map(it => it.to)
        const list = await m.createQueryBuilder()
            .select('red.room_id', 'room_id')
            .addSelect('room.user_id', 'user_id')
            .addSelect('account.id', 'id')
            .from(KsRedPacket, 'red')
            .leftJoin(KsLiveRoom, 'room', 'room.id=red.room_id')
            .leftJoin(KsAccount, 'account', 'account.user_id=room.user_id')
            .where('red.type=:type', { type: '粉丝团' })
            .andWhere(`room.user_id not in (:...hasFollowIds)`, { hasFollowIds })
            .andWhere(`red.count>:count`, { count: 1 })
            .limit(body.count)
            .orderBy(`red.count`, 'DESC')
            .execute()
        return toSuccess(list)
    })
}